# $Id: testtmpl.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import optparse
import os
import sys

from django.core import exceptions
from django.core.management import base
from django.template import Context, Template

from djanet.lib import exception, ip, stdlib
from djanet.utils import grid

class Command(base.BaseCommand):
   option_list = (
         optparse.make_option("-f", "--filename", action = "store",
            help = "Template file to use", dest = "filename"),
         optparse.make_option("-m", "--model", action = "store",
            help = "Model name", dest = "model"),
         optparse.make_option("-a", "--app", action = "store",
            help = "App name", dest = "app"),
         ) + base.BaseCommand.option_list

   help = "Template testing program"

   def __init__(self):
      super(Command, self).__init__()
      self._fh = None

   def error(self, Message):
      self.close
      raise exception.CommandError, Message

   @property
   def close(self):
      if self._fh:
         self._fh.close()
         self._fh = None

   def handle(self, *args, **options):
      filename = None
      model = None
      app = None

      print args
      sys.exit(1)

      if "filename" in options:
         filename = options.get('filename')

      if "model" in options:
         model = options.get('model')

      if "app" in options:
         app = options.get('app')

      if filename and model and app:
         if os.path.exists(filename):
            try:
               self._fh = open(filename, "r")
            except IOError, message:
               self.error(message)
            else:
               template = Template(self._fh.read())
               gridinst = None
               try:
                  gridinst = grid.ModelGrid(app, model)
               except exception.GridError, message:
                  self.error(message)
               else:
                  print gridinst.grid.layout
                  table = { 'layout' : gridinst.grid.layout }
                  print template.render(Context(table))
            finally:
               self.close
